package util

import (
	"short-link/model"
	"time"
)

var (
	userCache     = make(map[string]*model.UserInfo)
	longUrlCache  = make(map[string]*model.ShortLink)
	shortUrlCache = make(map[string]*model.ShortLink)
)

func AddUserCache(userInfo *model.UserInfo) {
	userCache[userInfo.Platform+":"+userInfo.OpenId] = userInfo
}

func GetUserCache(platform, openId string) *model.UserInfo {
	item := userCache[platform+":"+openId]
	if item == nil {
		return nil
	}
	if item.DeletedAt.Valid {
		return nil
	}
	return item
}

func DelUserCache(platform, openId string) {
	delete(userCache, platform+":"+openId)
}

func AddShortLinkCache(shortLink *model.ShortLink) {
	longUrlCache[shortLink.LongUrlMd5] = shortLink
	shortUrlCache[shortLink.ShortUrlPart] = shortLink
}

func GetShortLinkCacheWithLongUrl(longUrlMd5 string) *model.ShortLink {
	item := longUrlCache[longUrlMd5]
	if item == nil {
		return nil
	}
	if item.ExpiredAt.Before(time.Now()) {
		return nil
	}
	return item
}

func GetShortLinkCacheWithShortUrl(shortUrlPart string) *model.ShortLink {
	item := shortUrlCache[shortUrlPart]
	if item == nil {
		return nil
	}
	if item.ExpiredAt.Before(time.Now()) {
		return nil
	}
	return item
}
